import sqlite3
import requests
import tkinter as tk
from tkinter import ttk, messagebox
from datetime import datetime

API_KEY="ae1718d4587744b0b79f940fbef69e77"
class BookManager:
    def __init__(self, master):
        self.master = master
        self.setup_db()
        self.setup_ui()
        
    def setup_db(self):
        """初始化数据库"""
        self.conn = sqlite3.connect('books.db')
        self.cursor = self.conn.cursor()
        self.cursor.execute('''CREATE TABLE IF NOT EXISTS books
                            (id INTEGER PRIMARY KEY AUTOINCREMENT,
                             isbn TEXT UNIQUE,
                             title TEXT,
                             authors TEXT,
                             publisher TEXT,
                             publish_date TEXT,
                             pages INTEGER,
                             add_time TIMESTAMP)''')
        self.conn.commit()

    def setup_ui(self):
        """创建图形界面"""
        self.master.title("图书管理系统")
        
        # 输入区域
        input_frame = ttk.Frame(self.master, padding=10)
        input_frame.pack(fill=tk.X)
        
        ttk.Label(input_frame, text="ISBN号：").grid(row=0, column=0)
        self.isbn_entry = ttk.Entry(input_frame, width=20)
        self.isbn_entry.grid(row=0, column=1, padx=5)
        self.isbn_entry.bind("<Return>", lambda e: self.add_book())  # 支持扫码枪回车
        
        ttk.Button(input_frame, text="添加图书", command=self.add_book).grid(row=0, column=2, padx=5)
        ttk.Button(input_frame, text="搜索图书", command=self.search_books).grid(row=0, column=3)
        
        # 图书列表
        columns = ("id", "title", "authors", "isbn", "publisher", "add_time")
        self.tree = ttk.Treeview(self.master, columns=columns, show='headings', height=15)
        
        # 设置列属性
        self.tree.heading("id", text="ID")
        self.tree.heading("title", text="书名")
        self.tree.heading("authors", text="作者")
        self.tree.heading("isbn", text="ISBN")
        self.tree.heading("publisher", text="出版社")
        self.tree.heading("add_time", text="入库时间")
        self.tree.column("id", width=50)
        self.tree.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 加载数据
        self.load_books()

    def get_book_info(self, isbn):
        url = f"http://data.isbn.work/openApi/getInfoByIsbn?isbn={isbn}&appKey={API_KEY}"
        try:
            response = requests.get(url, timeout=50)
            data = response.json()
            # TODO检查data返回的数据是否有效
            
            info_dict=data["data"]
            return {
                "title": info_dict.get("bookName", "未知"),
                "authors": ", ".join(info_dict.get("author", ["未知"])),
                "publisher": info_dict.get("press", "未知"),
                "publish_date": info_dict.get("pressDate", "未知"),
                "pages": info_dict.get("pages", 0),
                "price": info_dict.get("price", "未知"),  
                "summary": info_dict.get("bookDesc", "") 
            }
        except Exception as e:
            messagebox.showerror("错误", f"获取图书信息失败: {str(e)}")
            return None
    
    def add_book(self):
        """添加图书"""
        isbn = self.isbn_entry.get().strip()
        if not isbn:
            messagebox.showwarning("提示", "请输入ISBN号")
            return
        
        if self.book_exists(isbn):
            messagebox.showinfo("提示", "该图书已存在")
            self.isbn_entry.delete(0, tk.END)
            return
        
        book_info = self.get_book_info(isbn)
        if not book_info:
            return
            
        try:
            self.cursor.execute('''INSERT INTO books 
                                  (isbn, title, authors, publisher, publish_date, pages, add_time)
                                  VALUES (?,?,?,?,?,?,?)''',
                               (isbn,
                                book_info["title"],
                                book_info["authors"],
                                book_info["publisher"],
                                book_info["publish_date"],
                                book_info["pages"],
                                datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
            self.conn.commit()
            self.load_books()
            self.isbn_entry.delete(0, tk.END)
            messagebox.showinfo("成功", "图书添加成功！")
        except Exception as e:
            messagebox.showerror("错误", f"数据库错误: {str(e)}")

    def book_exists(self, isbn):
        """检查图书是否存在"""
        self.cursor.execute("SELECT id FROM books WHERE isbn=?", (isbn,))
        return self.cursor.fetchone() is not None

    def load_books(self, search_key=None):
        """加载/刷新图书列表"""
        for row in self.tree.get_children():
            self.tree.delete(row)
            
        query = "SELECT id, title, authors, isbn, publisher, add_time FROM books"
        params = ()
        if search_key:
            query += " WHERE title LIKE ? OR authors LIKE ? OR isbn LIKE ?"
            search_term = f"%{search_key}%"
            params = (search_term, search_term, search_term)
            
        self.cursor.execute(query, params)
        for row in self.cursor.fetchall():
            self.tree.insert("", tk.END, values=row)

    def search_books(self):
        """搜索图书"""
        search_window = tk.Toplevel(self.master)
        search_window.title("搜索图书")
        
        ttk.Label(search_window, text="输入搜索关键词：").pack(pady=5)
        search_entry = ttk.Entry(search_window, width=30)
        search_entry.pack(pady=5)
        
        def do_search():
            self.load_books(search_entry.get().strip())
            search_window.destroy()
            
        ttk.Button(search_window, text="搜索", command=do_search).pack(pady=5)

if __name__ == "__main__":
    root = tk.Tk()
    app = BookManager(root)
    root.mainloop()